import { defineStore } from 'pinia'
import { ref } from 'vue'
import { apiLogin, apiLogout, apiGetUserInfo } from '@/api/system/user'
import { apiConfigPublicList } from '@/api/system/config'

export interface UserInfo {
  id: string
  username: string
  nickname?: string
  email?: string
  phone?: string
  gender?: number
  avatar?: string
  bio?: string
  deptId?: number
  roleArr?: string[]
}

export const useUser = defineStore('user', () => {
  // 登录状态
  const isAuthenticated = ref<boolean>(false)
  // 用户信息
  const userInfo = ref<UserInfo | null>(null)
  // 系统参数
  const params = ref<any>({})

  /**
   * 初始化数据
   */
  const initData = async () => {
    // 获取用户信息
    await getUserInfo()
    // 获取系统参数
    await getConfigPublicList()
  }

  /**
   * 设置登录状态
   * @param status 登录状态
   */
  const setLoginStatus = (status: boolean) => {
    isAuthenticated.value = status
  }

  /**
   * 设置用户信息
   * @param info 用户信息
   */
  const setUserInfo = (info: any) => {
    userInfo.value = info
    try {
      if (info) localStorage.setItem('userInfo', JSON.stringify(info))
      else localStorage.removeItem('userInfo')
    } catch (e) {
      console.error('保存用户信息失败:', e)
    }
  }

  /**
   * 设置登录令牌
   * @param token 登录令牌
   */
  const setAccessToken = (token: string | null) => {
    try {
      if (token) localStorage.setItem('accessToken', token)
      else localStorage.removeItem('accessToken')
    } catch (e) {
      console.error('保存 accessToken 失败:', e)
    }
  }

  /**
   * 用户登录
   * @param params 登录参数
   * @returns
   */
  const login = async (params: any) => {
    const response = await apiLogin(params)
    const { code, data } = response || {}
    if (code === 200) {
      setAccessToken(data)
      const subResult = await getUserInfo()
      if (subResult && subResult.code === 200) {
        setLoginStatus(true)
        setUserInfo(subResult.data || subResult.data?.data)
      }
      return subResult
    }
    return response
  }

  /**
   * 用户退出
   */
  const logout = async () => {
    const response = await apiLogout()
    const { code } = response || {}
    if (code === 200) {
      setLoginStatus(false)
      setUserInfo(null)
      setAccessToken(null)
      try {
        localStorage.removeItem('isAuthenticated')
        localStorage.removeItem('userInfo')
        localStorage.removeItem('accessToken')
      } catch (e) {
        console.error('清除 localStorage 失败:', e)
      }
    }
  }

  /**
   * 获取用户信息
   * @return
   */
  const getUserInfo = async () => {
    const res = await apiGetUserInfo()
    if (res && res.data) {
      setLoginStatus(true)
      setUserInfo(res.data)
    }
    return res
  }

  /**
   * 获取系统参数
   * @return
   */
  const getConfigPublicList = async () => {
    const res = await apiConfigPublicList()
    if (res && res.data) {
      params.value = res.data || {}
    }
  }

  return {
    isAuthenticated,
    userInfo,
    params,
    initData,
    setUserInfo,
    login,
    logout,
  }
})
